package com.suppor.rpc.proto.serialization;

import com.google.gson.Gson;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class JsonSerialization implements RpcSerializer {
    private static final Gson gson = new Gson();

    @Override
    public <T> byte[] serialize(T object) throws IOException {
        if (object instanceof String) {
            return ((String) object).getBytes(StandardCharsets.UTF_8);
        }
        return gson.toJson(object).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws IOException {
        if (null == data || null == clazz) {
            return null;
        }

        T result = gson.fromJson(new String(data, StandardCharsets.UTF_8), clazz);
        return result;
    }
}
